package feizhou.untils.tools.io;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * IO流程工具类
 *
 * @author <a href="920786312@qq.com">周飞</a>
 * @since 2023/7/26 16:18
 */
public class IOStreamUtil {
    public static Logger logger = LoggerFactory.getLogger(IOStreamUtil.class);


    /**
     * 在读取大型文件时，使用 BufferedReader.readLine()方法逐行读取，而不是一次性读取整个文件到内存中。。
     *
     * @return
     */
    public static List<String> read_bufferedReader(String filePath) {
        List<String> lines = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }

    /**
     * 读取inputStream的所有字节。
     *
     * @return
     */
    public static byte[] toBytes(InputStream inputStream) throws IOException {
        //输入
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将字节写入到指定文件中
     *
     * @return
     */
    public static void write_bufferedOutputStream(byte[] data, String filePath) {
        try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath))) {
            // 将byte[]数据写入到文件中
            outputStream.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 将多行内容写入到指定文件中
     *
     * @return
     */
    public static void write_bufferedWriter(List<String> lines, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (String line : lines) {
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将多行内容写入到指定文件中
     *
     * @return
     */
    public static void write_bufferedWriter(String content, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(content);
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 构建目录
     *
     * @return
     */
    public static void mkdirs(String dirPath) {
        File file = new File(dirPath);
        file.mkdirs();
    }

    /**
     * 读取文件内容，每一行的内容，通过separator分隔符连接，最终返回一个字符串
     *
     * @param filePath  文件的路径
     * @param separator 分隔符
     * @return void
     * @author <a href="920786312@qq.com">周飞</a>
     * @since 2023/8/3 10:00
     */
    public static String getString(String filePath, String separator) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append(separator);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (sb.length() > 0) {
            sb = sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    /**
     * 使用字节方法，将一个文件写到另外一个文件中,高效缓存，字节数组读取，建议使用
     *
     * @param src  原文件路径
     * @param dest 目标文件路径
     * @return void
     * @author <a href="920786312@qq.com">周飞</a>
     * @since 2023/8/28 11:57
     */
    public static void fileCopy(String src, String dest) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(src));
            bos = new BufferedOutputStream(new FileOutputStream(dest));
            byte[] bys = new byte[1024];
            int len = 0;
            while ((len = bis.read(bys)) != -1) {
                bos.write(bys, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * inputStream 转 MultipartFile
     *
     * @return MultipartFile
     * @author <a href="920786312@qq.com">周飞</a>
     * @since 2023/9/22 16:14
     */
    public static MultipartFile toMultipartFile(InputStream inputStream, String fileName) {
        FileItem fileItem = createFileItem(inputStream, fileName);
        MultipartFile multi = new CommonsMultipartFile(fileItem);
        return multi;
    }


    /**
     * FileItem类对象创建
     *
     * @param inputStream inputStream
     * @param fileName    fileName
     * @return FileItem
     */
    public static FileItem createFileItem(InputStream inputStream, String fileName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "file";
        FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        OutputStream os = null;
        //使用输出流输出输入流的字节
        try {
            os = item.getOutputStream();
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            inputStream.close();
        } catch (IOException e) {
            logger.error("Stream copy exception", e);
            throw new IllegalArgumentException("文件上传失败");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    logger.error("Stream close exception", e);

                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("Stream close exception", e);
                }
            }
        }

        return item;
    }


    public static void main(String[] args) throws Exception {
//        String path = "C:\\Users\\26372\\Desktop\\图片\\IMG_7953.jpg";
//        File file = new File(path);
//        FileInputStream ins = new FileInputStream(file);
//        toMultipartFile(ins, file.getName());

        String path = "C:\\Users\\26372\\Desktop\\temp\\1.zip";

        byte[] bytes = toBytes(new FileInputStream(path));
        System.out.println(bytes);


    }
}